import json
import logging
import traceback

import requests


class PushHandler(logging.Handler):
    """
    A class which sends records to a Web server, using either GET or
    POST semantics.
    """
    def __init__(self, base_url):
        """
        Initialize the instance with the host, the request URL, and the method
        ("GET" or "POST")
        """
        logging.Handler.__init__(self)
        self.base_url = base_url


    def mapLogRecord(self, record):
        """
        Default implementation of mapping the log record into a dict
        that is sent as the CGI data. Overwrite in your class.
        Contributed by Franz Glasner.
        """
        if isinstance(record.exc_info, tuple) and len(record.exc_info) > 2:
            record.stack_info = r''.join(traceback.format_exception(record.exc_info[0], record.exc_info[1], record.exc_info[2]))
            record.exc_text = str(record.exc_info[1])
        _map = record.__dict__
        for k,v in _map.items():
            # if isinstance(v, unicode):
            #     _map[k] = v.encode("utf8")
            if v is None:
                _map[k] = r''
        return _map

    def emit(self, record):
        """
        Emit a record.

        Send the record to the Web server as a percent-encoded dictionary
        """
        data = self.mapLogRecord(record)
        requests.post(self.base_url + "log/save", data)
        # self.sender.log(data)